package com.sgb.kjwl.view.ui.fragment.transport;

import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragCargoManageBinding;
import com.sgb.kjwl.model.entity.self.GoodsManageItemData;
import com.sgb.kjwl.model.entity.self.GoodsMangeResultEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.self.GoodsManageEvent;
import com.sgb.kjwl.view.ui.activity.self.logistics.OfferListGeneralGoodsActivity;
import com.sgb.kjwl.view.ui.activity.self.logistics.OfferOwnerListActivity;
import com.sgb.kjwl.view.ui.activity.self.logistics.PublishCargoActivity;
import com.sgb.kjwl.view.ui.activity.transport.driver.goods.FreightPrjDetailActivity;
import com.sgb.kjwl.view.ui.activity.transport.driver.goods.GeneralPrjDetailActivity;
import com.sgb.kjwl.view.ui.activity.transport.owner.TransportOrderDetailOwnerActivity;
import com.sgb.kjwl.view.ui.adapter.self.logistics.CargoManageItemAdapter;
import com.sgb.kjwl.viewmodel.self.logistics.CargoManageModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.ArrayUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 杨畔
 * @date: 2020/12/28 10:59
 * @Description: 货源管理内容页
 */
@Route(path = AppRouteConstant.WuLui.ROUTER_PATH_GENERALPRJDETAILACTIVITY)
public class CargoManageItemFragment extends AppLazyFragment {
    CargoManageModel viewModel;
    FragCargoManageBinding binding;
    //货源列表
    private List<GoodsManageItemData> mList;
    private CargoManageItemAdapter mAdapter;
    //
    private boolean mIsGeneralGoods;
    private int mPattern;
    private int mState;
    private int mPage = 1;

    public static CargoManageItemFragment newInstance(int state, boolean isGeneralGoods) {
        CargoManageItemFragment fragment = new CargoManageItemFragment();
        Bundle args = new Bundle();
        args.putInt(RouterKey.TYPE, state);
        args.putBoolean(RouterKey.BOOLEAN, isGeneralGoods);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        viewModel = new ViewModelProvider(this).get(CargoManageModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.frag_cargo_manage, container, false);
        binding.setLifecycleOwner(this);
        return binding.getRoot();
    }

    @Override
    protected void onLazyLoad() {
        initIntentParams();
        initRecycler();
        initEvent();
        initData();
    }

    private void initIntentParams() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            mState = getArguments().getInt(RouterKey.TYPE);
            mIsGeneralGoods = getArguments().getBoolean(RouterKey.BOOLEAN, true);
            mPattern = mIsGeneralGoods ? 0 : 1;
        }
    }

    private void initRecycler() {
        mList = new ArrayList<>();
        mAdapter = new CargoManageItemAdapter(mList);
        binding.rvCargoManage.setLayoutManager(new LinearLayoutManager(getActivity()));
        if (getActivity() != null) {
            DividerDecoration.builder(getActivity())
                    .showFirstDivider()
                    .color(Color.TRANSPARENT)
                    .size(10, TypedValue.COMPLEX_UNIT_DIP)
                    .build()
                    .addTo(binding.rvCargoManage);
        }
        mAdapter.bindToRecyclerView(binding.rvCargoManage);
    }

    private void initEvent() {
        binding.srlCargoManage.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                viewModel.getGoodsManagerList(getContext(), mPage, mState, mPattern);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshData();
            }
        });
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            GoodsManageItemData info = mList.get(position);
            itemClick(view, info);
        });
        //接口回调
        viewModel.ldGoods.observe(this, this::refreshUIByData);
    }

    private void initData() {
        refreshData();
    }

    /**
     * 列表按钮点击事件
     */
    private void itemClick(View view, GoodsManageItemData info) {
        if (view.getId() == R.id.cl_item_cm) {
            //跳转货源详情
            if (info.getPattern() == 1) {
                FreightPrjDetailActivity.start(getActivity(), info.getNo(), false, true);
            } else {
                GeneralPrjDetailActivity.start(getActivity(), info.getNo(), info.getPattern(), true);
            }
        } else if (view.getId() == R.id.tv_item_cm_order && getActivity() != null) {
            //成交订单详情
            ActivityJump.jumpToActivity(getActivity(), TransportOrderDetailOwnerActivity.class,
                    Pair.create("no", info.getOrderNo()),
                    Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.GOODS_OWNER));
        } else if (view.getId() == R.id.tv_item_cm_edit) {
            //货源编辑
            PublishCargoActivity.start(getActivity(), info.getNo(), true);
        } else if (view.getId() == R.id.tv_item_cm_down) {
            //上下架后注意刷新页面全部，待接单和已下架页
            dropOffDialog(info);
        } else if (view.getId() == R.id.tv_item_cm_del) {
            //删除货源
            showDelDialog(info);
        } else if (view.getId() == R.id.tv_item_cm_offer_unit) {
            //判断是竞价货源还是普通货源
//            if (mIsGeneralGoods) {
                OfferListGeneralGoodsActivity.start(getActivity(), info.getNo(), info.getPattern() != null && info.getPattern() != 1);
//            } else {
//                OfferOwnerListActivity.start(getActivity(), info.getNo(), false);
//            }
        } else if (view.getId() == R.id.tv_item_cm_order_unit) {
            //todo 接单单位列表
            OfferOwnerListActivity.start(getActivity(), info.getNo(), true);
        }
    }

    public void refreshData() {
        if (mAdapter != null) {
            mPage = 1;
            viewModel.getGoodsManagerList(getContext(), mPage, mState, mPattern);
        }
    }

    /**
     * 删除提示
     */
    private void showDelDialog(GoodsManageItemData data) {
        new RoundDialog.Builder(getActivity())
                .title("温馨提示")
                .content("确定删除吗？")
                .confirmCallback(v -> viewModel.deleteGoods(getContext(), data))
                .show();
    }

    /**
     * 上下架提示
     */
    private void dropOffDialog(GoodsManageItemData item) {
        new RoundDialog.Builder(getActivity())
                .title("1".equals(item.getStatus())
                        ? "下架"
                        : "上架")
                .content("1".equals(item.getStatus())
                        ? "下架后前台不展示此信息，\n确认下架吗？"
                        : "上架后前台展示此信息，确认上架吗？")
                .confirmCallback(v -> viewModel.downAndUpGoods(getContext(), item))
                .show();
    }

    /**
     * 同步数据
     */
    private void refreshUIByData(GoodsMangeResultEntity listResponse) {
        binding.srlCargoManage.finishRefresh();
        binding.srlCargoManage.finishLoadMore();
        if (listResponse == null) {
            return;
        }
        //设置数据
        if (listResponse.getAppGoodsVoPage().getPageNumber() == 1) {
            mList.clear();
        }
        if (listResponse.getAppGoodsVoPage().getList() != null) {
            mList.addAll(listResponse.getAppGoodsVoPage().getList());
        }
        if (ArrayUtil.isNullOrEmpty(mList)) {
            mAdapter.setEmptyView(R.layout.layout_null_list_logistics);
        }
        mAdapter.notifyDataSetChanged();
        setTableCount(mIsGeneralGoods ? listResponse.getWaitingNum() : listResponse.getBiddingNum());
        //更新页码
        if (listResponse.getAppGoodsVoPage().getPageNumber() < listResponse.getAppGoodsVoPage().getPageSize()) {
            mPage = listResponse.getAppGoodsVoPage().getPageNumber() + 1;
            binding.srlCargoManage.setNoMoreData(false);
        } else {
            binding.srlCargoManage.finishLoadMoreWithNoMoreData();
        }
    }

    private void setTableCount(int count) {
        //只有竞价中货源有数字提示
        if (!mIsGeneralGoods && mState == 0) {
            EventBus.getDefault().post(GoodsManageEvent.make(EventConstant.EVENT_REFRESH_CARGO_MANAGE_TAB_COUNT, count).setObject(mIsGeneralGoods));
        }
    }
}
